package cn.itcast.filter;

import cn.itcast.utils.CurrentHolder;
import cn.itcast.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Slf4j
//@WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //1.获取请求的路径
        String url = request.getRequestURI();
        log.info("请求路径:{}", url);

        //2.判断是不是登录操作
        if (url.contains("login")) {
            //是登陆操作，直接放行
            log.info("登录请求 , 直接放行");
            filterChain.doFilter(request, response);
            return;
        }
        //3.如果不是登录请求,那么就需要获取请求头中的令牌
        String token = request.getHeader("token");
        log.info("请求头中的令牌:{}", token);

        //4.判断令牌是否为null
        if ( token == null  ) {
            log.error("获取到jwt令牌为空, 返回错误结果");
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);//401  没有令牌
            return;
        }

        //5.解析token,若解析失败,返回错误结果
        try {
            Claims claims = JwtUtils.parseJWT(token);
            String str = claims.get("id").toString();
            Integer id = Integer.valueOf(str);
            CurrentHolder.setCurrentId(id);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("令牌解析失败, 返回错误结果");
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return;
        }

        //6.令牌通过,放行请求
        log.info("令牌合法, 放行");
        filterChain.doFilter(request, response);

        //7.释放资源
        CurrentHolder.remove();
    }
}
